package com.example.demotest.service;
import com.example.demotest.pojo.*;
import com.example.demotest.pojo.dto.ProductEditDto;
import com.example.demotest.pojo.dto.ProductRequestDto;
import com.example.demotest.repository.ProductCategoryRepository;
import com.example.demotest.repository.ProductRepository;
import jakarta.persistence.criteria.Predicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
//import org.springframework.data.domain.Page;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
/*
*负责人：孟瑞航
* 功能：1.保存商品：我们需要从 ProductRequest 中提取商品信息，并将它保存到数据库中。
       2.关联用户：商品发布需要关联到当前登录的用户（通过 userId）。
       3.返回商品 ID：商品发布成功后，我们需要返回该商品的 ID
* 实现：1.依赖于ProductRepository，与数据库进行交互
*      2.将ProductRequestDto转换为 Product 实体类以保存到数据库
*
* */


@Service
public class ProductService implements IProductService{
    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private ProductCategoryRepository categoryRepository;
    /*
    * 功能：创建商品，并设置为待审核状态
    * 该方法返回的是一个包含 数据库保存结果（含自动生成 ID） 的 Product 对象，可用于后续接口返回给前端
    * */
    @Override
    public Product publish(ProductRequestDto request, Integer userId) {
        ProductCategory category = categoryRepository.findById(request.getCategoryId())
                .orElseThrow(() -> new IllegalArgumentException("分类不存在，ID = " + request.getCategoryId()));
        // 创建商品实体并设置属性
        Product product = new Product();
        product.setProductName(request.getProductName());
        product.setProductDescription(request.getDescription());
        product.setProductPrice(request.getPrice());
        product.setProductCategory(category);
        product.setImages(request.getImages() != null ? String.join(",", request.getImages()) : null);
        product.setUserId(userId);
        product.setCreatedAt(LocalDateTime.now());
        product.setStatusCheck(ProductCheckStatus.PENDING);  // 设置商品状态为待审核
        product.setStatusSold(ProductSoldStatus.ON_SALE);
        // 保存商品至数据库，状态为待审核
        //管理员在数据库中查询待审核的商品进行审核，通过则修改审核状态字段(应有接口)
        Product saved = productRepository.save(product);  // ✅ 一定要保存后拿
        System.out.println("商品发布成功，ID: " + saved.getProductID());
        return saved;
    }
    /*
     * 通过商品id获取商品
     */
    @Override
    public Product getProductById(Integer productId) {
        // 查找商品并返回 Optional<Product>
        return productRepository.findById(productId).orElse(null);  // 如果商品不存在返回 null
    }

    /*
     * 编辑商品信息
     */
    @Override
    public ResponseMessage<Object> editProduct(Integer productId, ProductEditDto request, Integer userId) {
        // 查找商品
        Product product = getProductById(productId);
        // 进行权限检查
        if (product == null || !product.getUserId().equals(userId)) {
            return ResponseMessage.error(403, "无权编辑该商品");
        }
        if (request.getProductName() != null) product.setProductName(request.getProductName());
        if (request.getDescription() != null) product.setProductDescription(request.getDescription());
        if (request.getPrice() != null) product.setProductPrice(request.getPrice());
        if (request.getClassificationId() != null) {
            Optional<ProductCategory> optionalCategory = categoryRepository.findById(request.getClassificationId());
            if (optionalCategory.isEmpty()) {
                return ResponseMessage.error(400, "分类不存在");
            }
            product.setProductCategory(optionalCategory.get());
        }
        if (request.getImages() != null) product.setImages(request.getImages() != null ? String.join(",", request.getImages()) : null);

        productRepository.save(product);
        return ResponseMessage.success();
    }

    /*
     * 下架商品
     */
    @Override
    public ResponseMessage offSaleProduct(Integer productId, Integer userId){
        Product product = productRepository.findById(productId).orElse(null);
        if(product == null) return ResponseMessage.error(404,"未找到该商品");
        if(product.getStatusSold() == ProductSoldStatus.OFF_SALE){
            return ResponseMessage.error(403,"该商品已下架");
        }
        if(!product.getUserId().equals(userId)){
            return ResponseMessage.error(403,"您无权限下架此商品");
        }
        product.setStatusSold(ProductSoldStatus.OFF_SALE);
        productRepository.save(product);
        return ResponseMessage.success();
    }

    //重新上架商品



    /*
     * 获取所有商品分类
     */
    @Override
    public List<ProductCategory> getAllClassification() {
        return categoryRepository.findAll();
    }

    /*
     * 获取某分类下的商品列表
     */
    @Override
    public Page<Product> getProductsByCategory(
            Integer classificationId,
            int page,
            int size,
            String time,
            Boolean hot,
            String priceSort,
            Double minPrice,
            Double maxPrice
    ) {
        // 创建动态查询条件
        Specification<Product> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 添加状态检查条件
            predicates.add(cb.equal(root.get("statusCheck"), ProductCheckStatus.APPROVED));
            predicates.add(cb.equal(root.get("statusSold"), ProductSoldStatus.ON_SALE));

            // 分类筛选
            if (classificationId != null && classificationId != 0) {
                predicates.add(cb.equal(root.get("productCategory").get("id"), classificationId));
            }

            // 价格区间筛选
            if (minPrice != null && minPrice > 0) {
                predicates.add(cb.greaterThanOrEqualTo(root.get("productPrice"), minPrice));
            }
            if (maxPrice != null && maxPrice > 0) {
                predicates.add(cb.lessThanOrEqualTo(root.get("productPrice"), maxPrice));
            }

            // 时间筛选
            if (time != null) {
                LocalDateTime now = LocalDateTime.now();
                switch (time) {
                    case "1day":
                        predicates.add(cb.greaterThanOrEqualTo(
                                root.get("createdAt"),
                                now.minusDays(1)
                        ));
                        break;
                    case "3days":
                        predicates.add(cb.greaterThanOrEqualTo(
                                root.get("createdAt"),
                                now.minusDays(3)
                        ));
                        break;
                }
            }

            return cb.and(predicates.toArray(new Predicate[0]));
        };

        // 创建排序
        Sort sort;
        if (Boolean.TRUE.equals(hot)) {
            try {
                // 按热度排序
                List<Product> products = productRepository.findPopularProducts(size, (page - 1) * size);
                long total = productRepository.countAllProducts();
                return new PageImpl<>(products, PageRequest.of(page - 1, size), total);
            } catch (Exception e) {
                // 如果native query失败，回退到使用JPA查询
                sort = Sort.by(Sort.Direction.DESC, "viewCount");
                Pageable pageable = PageRequest.of(page - 1, size, sort);
                return productRepository.findAll(spec, pageable);
            }
        } else if (priceSort != null && !priceSort.isEmpty()) {
            try {
                sort = Sort.by(
                        Sort.Direction.fromString(priceSort.toLowerCase()),
                        "productPrice"
                );
            } catch (IllegalArgumentException e) {
                sort = Sort.by(Sort.Direction.DESC, "productPrice");
            }
        } else {
            sort = Sort.by(Sort.Direction.DESC, "createdAt");
        }

        Pageable pageable = PageRequest.of(page - 1, size, sort);
        return productRepository.findAll(spec, pageable);
    }


    //获取我的商品,区分上下架
    @Override
    public List<Product> getMyProduct(Integer userId, ProductSoldStatus statusSold,ProductCheckStatus statusCheck) {
        return productRepository.findByUserIdAndStatusSoldAndStatusCheck(
                userId,
                statusSold,
                statusCheck
        );
    }

    //重新上架商品
    @Override
    public ResponseMessage<Object> republishProduct(Integer productId, Integer userId) {
        Product product = productRepository.findById(productId).orElse(null);
        if (product == null) {
            return ResponseMessage.error(404, "未找到该商品");
        }
        if (!product.getUserId().equals(userId)) {
            return ResponseMessage.error(403, "您无权限上架此商品");
        }
        if (product.getStatusSold() == ProductSoldStatus.ON_SALE) {
            return ResponseMessage.error(400, "该商品已处于上架状态");
        }

        product.setStatusSold(ProductSoldStatus.ON_SALE);
        productRepository.save(product);
        return ResponseMessage.success();
    }

    @Override
    @Transactional
    public void incrementViewCount(Integer productId) {
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new IllegalArgumentException("商品不存在，ID = " + productId));
        product.setViewCount(product.getViewCount() + 1);
        productRepository.save(product);
    }

    public Map<String, Object> fuzzySearch(String keyword, Integer page, Integer size) {
        try {
            // 创建分页对象
            Pageable pageable = PageRequest.of(page - 1, size);
            
            // 使用 JPA 的模糊查询，同时检查商品状态
            Page<Product> products = productRepository.findByProductNameContainingOrProductDescriptionContainingAndStatusCheckEquals(
                keyword, keyword, "APPROVED", pageable);
            
            // 处理图片URL
            List<Product> processedProducts = products.getContent().stream()
                .map(product -> {
                    // 处理图片URL
                    if (product.getImages() != null && !product.getImages().isEmpty()) {
                        String[] imageUrls = product.getImages().split(",");
                        product.setImages(imageUrls[0]); // 只保留第一张图片
                    }
                    return product;
                })
                .collect(Collectors.toList());
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("content", processedProducts);
            result.put("totalElements", products.getTotalElements());
            result.put("totalPages", products.getTotalPages());
            result.put("currentPage", page);
            
            return result;
        } catch (Exception e) {
            throw new RuntimeException("搜索失败: " + e.getMessage());
        }
    }
}
